<?php

namespace App\Http\Controllers;

use App\Models\User;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class WeChatController extends Controller
{
    private $miniProgram;
    //
    public function __construct()
    {
        $this->miniProgram = Factory::miniProgram([
            'app_id' => 'wxc61f978710df7450',
            'secret' => '365d32a03c3ccfc2dd816eabbab9983d'
        ]);
    }

    public function login(Request $request){
        $code = \request('code');
        $miniProgram = $this->miniProgram;
        $data = $miniProgram->auth->session($code);
        $weappOpenid = $data['openid'];
        $weixinSessionKey = $data['session_key'];
        $nickname = $request->nickname;
        $avatar = str_replace('/132', '/0', $request->avatar);//拿到分辨率高点的头像
        $country = $request->country?$request->country:'';
        $province = $request->province?$request->province:'';
        $city = $request->city?$request->city:'';
        $gender = $request->gender == '1' ? '1' : '2';//没传过性别的就默认女的吧，体验好些
        $language = $request->language?$request->language:'';

        $user = User::where('open_id', $weappOpenid)->first();
        if(is_null($user)){
            //要么是没注册，要么是通过手机号注册，所以需要绑定一下open——id
            $session_id = Str::random(32);
            Cache::put(
                'weapp_'.$session_id,
                [
                    'nickname' => $nickname,
                    'avatar' => $avatar,
                    'country' => $country,
                    'province' => $province,
                    'city' => $city,
                    'gender' => $gender,
                    'language' => $language,
                    'open_id' => $weappOpenid,
                    'session_key' => $weixinSessionKey,
                ],
                1000
            );
            return api_output([
                'status' => 'fail',
                'session_id' => $session_id
            ]);
        }else{
            //登录成功
            $token = auth()->login($user);
            return api_output([
                'status' => 'success',
                'access_token' => $token,
                'token_type' => 'bearer',
                'expires_in' => auth()->factory()->getTTL() * 60
            ]);
        }
    }

    public function loginByPhone(){
        $validator = validator(\request()->all(), [
            'session_id' => 'required|string',
            'iv' => 'required',
            'encryptedData' => 'required'
        ]);
        if ($validator->fails()) {
            return api_error('002');
        }

        $session = Cache::get('weapp_'.\request('session_id'));
        $iv = \request('iv');
        $encryptedData = \request('encryptedData');

        $decryptedData = $this->miniProgram->encryptor->decryptData($session['session_key'], $iv, $encryptedData);

        $user = User::where('phone', $decryptedData['purePhoneNumber'])->first();
        if(is_null($user)){
            // 不允许注册
            return api_error('014');
            //该手机号没有注册过，需要设置密码
            $session['phone'] = $decryptedData['purePhoneNumber'];
            $session_id = Str::random(32);
            Cache::put(
                'weapp_'.$session_id,
                [
                    'data' => $session
                ],
                1000
            );
            return api_output([
                'status' => 'fail',
                'session_id' => $session_id
            ]);
        }else{
            //该手机号注册过，同步一下微信资料，登录成功
            $user->open_id = $session['open_id'];
            $user->country = $session['country'];
            $user->province = $session['province'];
            $user->city = $session['city'];
            $user->gender = $session['gender'];
            $user->avatar = $session['avatar'];
            $user->language = $session['language'];
            $user->save();
            $token = auth()->login($user);
            return api_output([
                'status' => 'success',
                'access_token' => $token,
                'token_type' => 'bearer',
                'expires_in' => auth()->factory()->getTTL() * 60
            ]);
        }
    }

    public function setPassword(){
        $validator = validator(\request()->all(), [
            'session_id' => 'required|string',
            'password' => 'required|string',
        ]);
        if ($validator->fails()) {
            return api_error('002');
        }

        $session = Cache::get('weapp_'.\request('session_id'))['data'];
        $password = \request('password');
        $user = new User();
        $user->name = $session['nickname'];
        $user->phone = $session['phone'];
        $user->password = hash('sha256', $password);
        $user->invitation_code = Str::random(32);
        $user->open_id = $session['open_id'];
        $user->country = $session['country'];
        $user->province = $session['province'];
        $user->avatar = $session['avatar'];
        $user->city = $session['city'];
        $user->gender = $session['gender'];
        $user->language = $session['language'];
        $user->save();
        $token = auth()->login($user);
        return api_output([
            'status' => 'success',
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }
}
